const inquirer = require('inquirer')
const Handlebars = require('handlebars')
const path = require('path')
const fs = require('fs')
const { Transform } = require('stream')

module.exports = (projectName) => {
  const questions = [
    {
      type: 'input',
      name: 'desc',
      message: '您的项目描述：',
      default: 'boom'
    },
    {
      type: 'input',
      name: 'author',
      message: '您的姓名：',
    }
  ]

  return inquirer.prompt(questions).then(answers => {
    // handlebars 的值
    const data = { projectName, ...answers }
    
    return new Promise((resolve, reject) => {
      try {
        console.log('创建中...')
        create(projectName, data)
        resolve()
      } catch (error) {
        reject(error)
      }
    })
  })
};

// 创建项目
function create(projectName, data) {
  // 模板文件所在目录
  const src = path.join(__dirname, '../templates')

  const cwd = process.cwd()
  // 要创建的项目所在目录
  const dest = path.join(cwd, projectName)


  // 编译 Handlebars 的转化流
  const createTransform = () => new Transform({
    transform: (chunk, encoding, cb) => {
      const input = chunk.toString()
      const output = Handlebars.compile(input)(data)
      cb(null, output)
    }
  })

  copy(src, dest, createTransform)
}

// 复制模板文件到指定目录
function copy(src, dest, createTransform) {
  // 创建目录
  fs.mkdirSync(dest)

  // 读取目录中的所有文件/目录
  let paths = fs.readdirSync(src)
  paths.forEach(path => {
    let _src = `${src}/${path}`
    let _dest = `${dest}/${path}`

    // 获取路径的属性
    let st = fs.statSync(_src)
    // 为文件
    if (st.isFile()) {
      // 创建读取流
      let read = fs.createReadStream(_src);

      // 创建写入流
      let write = fs.createWriteStream(_dest);

      // 通过管道来传输流
      read
        .pipe(createTransform()) // 每次使用的流都是新的
        .pipe(write)

    } else if (st.isDirectory()) {
      // 如果是目录则递归调用自身
      copy(_src, _dest, createTransform);
    }
  })
}
